package com.tianpengtech.common.pay.weixin.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.fairorder.FairOrder;
import com.tianpengtech.common.model.fairsalary.FairSalary;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.pay.service.PayService;
import com.tianpengtech.common.pay.weixin.WxPayParamBuilder;
import com.tianpengtech.common.pay.weixin.required.WxPayUtil;
import com.tianpengtech.common.util.JsonUtil;
import com.tianpengtech.front.web.login.LoginService;

public class PayController extends Controller {

	public void orderList() {

		int pageNum = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGENUM, GlobalConfigConstant.DEFAULT_VALUE_PAGENUM);
		int pageSize = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGESIZE,
				GlobalConfigConstant.DEFAULT_VALUE_PAGESIZE);
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);
		String sql = " from fair_order where user=?  order by id desc";
		Page<FairOrder> page = FairOrder.dao.paginate(pageNum, pageSize, "select *", sql, userId);
		for (FairOrder r : page.getList()) {
			r.set(FairOrder.TOTAL_FEE, r.total_fee());
			r.set(FairOrder.TRADE_TYPE, r.trade_type());
			r.put("status_str", r.status());
		}
		renderJson(page);
	}

	public void index() {

		String sql = "select * from fair_user_salary where user_id=? limit 1";
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);
		setAttr("salary", FairSalary.dao.findFirst(sql, userId));
		renderTemplate("order-list.html");
	}

	public void accountCharge() {
		String sql = "select * from fair_user_salary where user_id=? limit 1";
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);
		setAttr("salary", FairSalary.dao.findFirst(sql, userId));
		renderTemplate("account-charge.html");
	}

	public void wxQrCode() {
		String nonceStr = WxPayUtil.generateNonceStr();
		String out_trade_no = WxPayParamBuilder.orderId();
		out_trade_no = out_trade_no + "_" + WxPayParamBuilder.randomInt();
		String name = getPara("name");
		int total_fee = getParaToInt("total_fee");
		total_fee = total_fee * 100;
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);
		try {
			String sign = WxPayParamBuilder.createWxPaySignWithNative(name, nonceStr, out_trade_no, total_fee + "");
			Map<String, Object> qrCodeUrl = WxPayParamBuilder.fetchNativeQrCode(name, nonceStr, out_trade_no,
					total_fee + "", sign, userId);
			renderJson(JsonUtil.printObject(qrCodeUrl));
		} catch (Exception e) {
			renderJson(JsonUtil.printError("无效二维码信息，请刷新页面重试"));
		}
	}

	public void missionQrCode() {
		
		String nonceStr = WxPayUtil.generateNonceStr();
		String out_trade_no = WxPayParamBuilder.orderId();
		out_trade_no = out_trade_no + "_" + WxPayParamBuilder.randomInt();
		int objId = getParaToInt("objId", 0);
		Task task = Task.dao.findById(objId);
		double total_fee = task.getDouble(Task.TASK_PRICE)*task.getInt(Task.WH_NUMBER);
		String name = task.getStr(Task.TASK_TITLE);
		name = "任务《"+name+"》付款";
		total_fee = total_fee * 100;
		
		//假如是指定网红，则每一名多收取额外的数量的钱
		
		if(task.getInt(Task.EXTENSION_TYPE)==Task.EXT_TYPE_ZD){
			int num = task.getInt(Task.WH_NUMBER);
            Dictionary dictionary = DictionaryDao.ME.readDirecotryByCode(Dictionary.EXTRA_FEE);
            int totalExtraFee = num*Integer.parseInt(dictionary.get(Dictionary.NAME));
            total_fee = total_fee+totalExtraFee*100;
		}
		
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);
		int fee = (int)total_fee;
		try {
			String sign = WxPayParamBuilder.createWxPaySignWithNative(name, nonceStr, out_trade_no, fee + "");

			// 检查当前任务的订单是否存在，存在就在1个小时内使用已经存在的付款信息
			String sql = "select * from fair_order where obj_id=? and opt_type=?";
			FairOrder order = FairOrder.dao.findFirst(sql, objId, FairOrder.OPT_TYPE_TASK);
			// 获取当前时间是否超过了二维码的过期时间
			Date now = new Date();
			boolean isExpire = (order == null) ? true
					: (now.getTime() - order.getDate(FairOrder.CREATE_TIME).getTime()) > 3600 * 1000;
			Map<String, Object> qrCodeUrl;
			
			boolean isPayed = (null!=null)?order.getInt(FairOrder.STATUS) == FairOrder.STATUS_STANDBY:false;
			if ((order == null || isExpire) && !isPayed) {// 订单有效时间1个小时
				qrCodeUrl = WxPayParamBuilder.fetchNativeQrCode(name, nonceStr, out_trade_no, fee + "", sign,
						userId, objId, FairOrder.OPT_TYPE_TASK);
				renderJson(JsonUtil.printObject(qrCodeUrl));
				return;
			} else if (order.getInt(FairOrder.STATUS) == FairOrder.STATUS_STANDBY) {
				qrCodeUrl = new HashMap<String, Object>();
				qrCodeUrl.put("id", order.getInt(FairOrder.ID));
				qrCodeUrl.put("qrCodeUrl", order.getStr(FairOrder.PAY_URL));
				renderJson(JsonUtil.printObject(qrCodeUrl));
				return;
			} else if (order.getInt(FairOrder.STATUS) == FairOrder.STATUS_CANCEL) {
				renderJson(JsonUtil.printError("取消了订单"));
			} else if (order.getInt(FairOrder.STATUS) == FairOrder.STATUS_PAYED) {
				renderJson(JsonUtil.printError("已经支付了订单"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			renderJson(JsonUtil.printError("无效二维码信息，请刷新页面重试"));
		}
	}

	public void continuPay() {
		String out_trade_no = getPara("order_no", "");
		int id = getParaToInt("id");
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId = loginUser.getLong(User.ID);

		String nonceStr = WxPayUtil.generateNonceStr();
		try {
			FairOrder order = FairOrder.dao.findById(id);
			String name = order.getStr(FairOrder.ORDER_DESC);
			if (order == null) {
				renderJson(JsonUtil.printError("当前数据记录不存在"));
				return;
			} else if (!order.getStr(FairOrder.ORDER_NO).equals(out_trade_no)) {
				renderJson(JsonUtil.printError("当前订单号与数据库里不一致"));
				return;
			}
			int total_fee = order.getInt(FairOrder.TOTAL_FEE);
			String weixinTradeNo = WxPayParamBuilder.randomInt();
			weixinTradeNo = out_trade_no + "_" + weixinTradeNo;
			order.set(FairOrder.TRADE_TYPE, FairOrder.NATIVE);
			order.set(FairOrder.UNIQUE_ID, weixinTradeNo).update();
			String sign = WxPayParamBuilder.createWxPaySignWithNative(name, nonceStr, weixinTradeNo, total_fee + "");
			Map<String, Object> result = WxPayParamBuilder.fetchNativeQrCode(name, nonceStr, weixinTradeNo,
					total_fee + "", sign, userId);
			String url = (String) result.get("qrCodeUrl");
			renderJson(JsonUtil.printSuccess(url));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(JsonUtil.printError("无效二维码信息，请刷新页面重试"));
		}
	}

	public void cancleOrder() {
		try {
			int id = getParaToInt("id");
			String orderNo = getPara(FairOrder.ORDER_NO);
			User loginUser = getAttr(LoginService.loginAccountCacheName);
			long userId = loginUser.getLong(User.ID);
			new PayService().cancleOrder(id, orderNo, userId);
			renderJson(JsonUtil.printSuccess("操作成功"));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}

	public void queryOrderStatus() {
		int id = getParaToInt("id");
		FairOrder order = FairOrder.dao.findById(id);
		if (order.getInt(FairOrder.STATUS) == FairOrder.STATUS_PAYED) {
			renderJson(JsonUtil.printSuccess("订单已经支付完成"));
		} else {
			renderJson(JsonUtil.printError("等待支付中..."));
		}
	}

	private void updateUserSalary() {

		Record record = Db.findFirst("select * from fair_order where unique_id=? limit 1",
				"20171204154725707_154725707");
		new PayService().updateUserSalary(record);
	}

	@Clear
	public void payCallBack() {

		StringBuffer sb = new StringBuffer();
		ServletInputStream instream;
		try {
			instream = getRequest().getInputStream();
			int len = -1;
			byte[] buffer = new byte[1024];
			while ((len = instream.read(buffer)) != -1) {
				sb.append(new String(buffer, 0, len));
			}
			instream.close();
			Map<String, String> valueMap = WxPayUtil.xmlToMap(sb.toString());// 接受微信的通知参数
			new PayService().savePayOrderLog(sb.toString(), valueMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJson();
	}

	public void salaryPay(){
		int id = getParaToInt("id",0);
		int taskId = getParaToInt("taskId",0);
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId=loginUser.getLong(User.ID);
		Task task = Task.dao.findById(taskId);
		if(task!=null){
			double totalFee = task.getDouble(Task.TASK_PRICE)*task.getInt(Task.WH_NUMBER)*100;
			String sql="select * from fair_user_salary where user_id=? limit 1";
	    	Record userSalary = Db.findFirst(sql,userId);
	    	double salary = (userSalary==null)?0:(userSalary.getInt("salary"));
    		if(salary>=totalFee){
    			
    			FairOrder order = FairOrder.dao.findById(id);
    			if(order!=null && order.getInt(FairOrder.STATUS)!=FairOrder.STATUS_PAYED){
    				double left = salary-totalFee;
        			userSalary.set("salary", left);
        			Db.update("fair_user_salary", userSalary);
    				order.set(FairOrder.ID, id);
        			order.set(FairOrder.STATUS, FairOrder.STATUS_PAYED);
        			order.update();
    			}else{
    				renderJson(JsonUtil.printError("当前订单已经支付过了，请勿重复操作"));
    				return;
    			}
    			renderJson(JsonUtil.printSuccess("余额支付成功"));
    		}else{
    			renderJson(JsonUtil.printError("当前帐号余额不足,支付失败"));
    		}
		}else{
			renderJson(JsonUtil.printError("当前任务信息无效"));
		}
	}
	
	public void createSalaryPayOrder(){
		int id = getParaToInt("id",0);
		String out_trade_no = WxPayParamBuilder.orderId();
		out_trade_no = out_trade_no + "_" + WxPayParamBuilder.randomInt();
		User loginUser = getAttr(LoginService.loginAccountCacheName);
		long userId=loginUser.getLong(User.ID);
		Task task = Task.dao.findById(id);
		if(task!=null){
			double totalFee = task.getDouble(Task.TASK_PRICE)*task.getInt(Task.WH_NUMBER)*100;
			String name = "任务《"+ task.getStr(Task.TASK_TITLE)+"》余额付款";
			// 检查当前任务的订单是否存在，存在就在1个小时内使用已经存在的付款信息
			String sql = "select * from fair_order where obj_id=? and opt_type=?";
			FairOrder order = FairOrder.dao.findFirst(sql,task.getInt(Task.ID), FairOrder.OPT_TYPE_TASK_SALARY);
			Date now = new Date();
			boolean isExpire = (order == null) ? true
					: (now.getTime() - order.getDate(FairOrder.CREATE_TIME).getTime()) > 3600 * 1000;
			if (order == null || isExpire) {
				int i =new PayService().salaryPay(out_trade_no, userId, totalFee+"", name, task.getInt(Task.ID), FairOrder.OPT_TYPE_TASK_SALARY);
				renderJson(JsonUtil.printObject(i));
			}else if(order.getInt(FairOrder.STATUS)==FairOrder.STATUS_PAYED){
				renderJson(JsonUtil.printError("HAS_PAY"));
			}else{
				renderJson(JsonUtil.printObject(order.getInt(FairOrder.ID)));
			}
		}else{
			renderJson(JsonUtil.printError("当前任务信息不存在"));
		}
		
	}

	@Clear
	public void test() {

	}
}
